package com.carl.guli.service;

import com.carl.guli.common.util.FileUploadUtil;
import com.carl.guli.mapper.ScenicSpotMapper;
import com.carl.guli.model.ScenicSpot;
import com.carl.guli.model.ScenicSpotExample;
import com.carl.guli.model.ScenicSpotWithBLOBs;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.util.List;

/**
 * Created by youzm on 2017/5/8.
 */
@Service
public class ScenicSpotServiceImpl implements ScenicSpotService {

    @Value("${ftp.directory}")
    private String ftpPath;

    @Value("${ftp.pic}")
    private String ftpPic;

    @Value("${ftp.download}")
    private String ftpDownload;

    @Autowired
    private ScenicSpotMapper scenicSpotMapper;

    @Override
    public void AddScenicSpot(ScenicSpotWithBLOBs scenicSpot, CommonsMultipartFile[] introPic, CommonsMultipartFile[] backPic) throws Exception {
        if (!introPic[0].isEmpty()){
            String introPicUrl = FileUploadUtil.uploadImg(ftpPath + ftpPic, introPic[0]);
            scenicSpot.setIntroPic(ftpDownload + ftpPic + "/" + introPicUrl);
        }
        if (!backPic[0].isEmpty()){
            String backPicUrl = FileUploadUtil.uploadImg(ftpPath + ftpPic, backPic[0]);
            scenicSpot.setBackPic(ftpDownload + ftpPic + "/" + backPicUrl);
        }

        if (scenicSpot.getSpotId() == null){
            scenicSpotMapper.insertSelective(scenicSpot);
        }

        if (scenicSpot.getSpotId() != null){
            scenicSpotMapper.updateByPrimaryKeySelective(scenicSpot);
        }
    }

    @Override
    public List<ScenicSpot> listScenicSpot() {
        ScenicSpotExample example = new ScenicSpotExample();
        example.setOrderByClause("sort desc");
        return scenicSpotMapper.selectByExample(example);
    }

    @Override
    public ScenicSpotWithBLOBs findScenicSpotById(Integer spotId) {
        ScenicSpotExample example = new ScenicSpotExample();
        example.createCriteria().andSpotIdEqualTo(spotId);
        List<ScenicSpotWithBLOBs> scenicSpots = scenicSpotMapper.selectByExampleWithBLOBs(example);
        if (scenicSpots.size() > 0){
            return scenicSpots.get(0);
        }
        return null;
    }

    @Override
    public void update2Top(Integer spotId) {
        int sort = scenicSpotMapper.findMaxSort();
        ScenicSpot record = new ScenicSpot();
        record.setSpotId(spotId);
        record.setSort(sort + 1);
        scenicSpotMapper.updateByPrimaryKeySelective(null);
    }

    @Override
    public void editScenicSpot(ScenicSpotWithBLOBs scenicSpot) {
        scenicSpotMapper.updateByPrimaryKeySelective(scenicSpot);
    }

    @Override
    public void delScenicSpot(Integer id) {
        scenicSpotMapper.deleteByPrimaryKey(id);
    }
}
